from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from datetime import datetime, timedelta
from hashlib import md5
from random import randint

INVITE_EXPIRES = getattr(settings, 'INVITE_EXPIRES', { 'days':30 })
INVITES_PER_USER = getattr(settings, 'INVITES_PER_USER', None)

try:
    import cPickle as pickle
    
except ImportError:
    import pickle

class Invite(models.Model):
    key = models.CharField(_("Unique invite key"), max_length=8, unique=True)
    expires = models.DateTimeField(_("Expires date"))
    email = models.EmailField(_("Recipient email"))
    sender = models.ForeignKey('auth.User', related_name='invites')
    _data = models.TextField(_("Additional data"), null=True, blank=True)
    
    class Meta:
        verbose_name = _("Invite")
        verbose_name_plural = _("Invites")

    def save(self, *args, **kwargs):
        if not self.key:
            while True:
                # Generating unique key
                self.key = md5(str(datetime.now())).hexdigest()[0:5+randint(0,3)]
                try:
                    Invite.objects.get(key=self.key)
                except Invite.DoesNotExist:
                    break
        if not self.expires:
            self.expires = datetime.now() + timedelta(**INVITE_EXPIRES)
        return super(Invite, self).save(*args, **kwargs)
    
    def _get_data(self):
        if self._data:
            return pickle.loads(unicode.encode(self._data))
        return None
            
    def _set_data(self, data):
        if data:
            self._data = pickle.dumps(data)
        
    data = property(_get_data, _set_data)
     
    def __repr__(self):
        return '<Invite from %s expires %s/>' % ( self.sender.username, self.expires.strftime("%m-%d-%Y %H:%M"), )
    
    def __unicode__(self):
        return u'Invite from %s expires %s' % ( self.sender.username, self.expires.strftime("%m-%d-%Y %H:%M"), )
    
    def get_absolute_url(self):
        return reverse('accept_invite', kwargs={ 'key': self.key })
    
if INVITES_PER_USER:    
    User.add_to_class('invites_left', models.PositiveIntegerField(_("Invites left"), default=settings.INVITES_PER_USER))

import dispatch
